package com.faxsun.core.catalog.service;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.broadleafcommerce.core.catalog.domain.Category;
import org.broadleafcommerce.core.catalog.domain.Product;
import org.broadleafcommerce.core.search.domain.ProductSearchCriteria;
import org.broadleafcommerce.core.search.domain.ProductSearchResult;
import org.broadleafcommerce.core.search.domain.SearchFacetDTO;
import org.broadleafcommerce.core.search.service.DatabaseSearchServiceImpl;
import org.springframework.stereotype.Service;

import com.faxsun.core.catalog.domain.FSProductImpl;

@Service("milkSearchService")
public class FSMilkCatalogServiceImpl extends DatabaseSearchServiceImpl {

	protected MilkCatalogCompator compator = new MilkCatalogCompator();

	@Override
	public ProductSearchResult findProductsByCategory(Category category,
			ProductSearchCriteria searchCriteria) {
		ProductSearchResult result = new ProductSearchResult();
		setQualifiedKeys(searchCriteria);
		List<Product> products = catalogService
				.findFilteredActiveProductsByCategory(category, searchCriteria);
		Collections.sort(products, compator);

		List<SearchFacetDTO> facets = getCategoryFacets(category);
		setActiveFacets(facets, searchCriteria);
		result.setProducts(products);
		result.setFacets(facets);
		result.setTotalResults(products.size());
		result.setPage(1);
		result.setPageSize(products.size());
		return result;
	}

}

class MilkCatalogCompator implements Comparator<Product> {

	@Override
	public int compare(Product o1, Product o2) {
		FSProductImpl p1 = (FSProductImpl) o1;
		FSProductImpl p2 = (FSProductImpl) o2;

		String c1 = "";
		if (p1 != null && p1.getCountry() != null) {
			c1 = p1.getCountry().getFriendlyType();
		}
		String c2 = "";
		if (p2 != null && p2.getCountry() != null) {
			c2 = p2.getCountry().getFriendlyType();
		}

		return c1.compareTo(c2);
	}

}
